﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace org.xisoft.game.utils
{
    public class AsyncTask<B,T>
        where B:class
       
    {
        private readonly Action<T> callback;
        private readonly ISynchronizeInvoke synchronizeInvoke;

         delegate void TestDelegate(T arg);

        public AsyncTask(ISynchronizeInvoke synchronizeInvoke, Action<T> callback)
        {
            this.callback = callback;
            this.synchronizeInvoke = synchronizeInvoke;
        }

        private void InvokeCallback(T result )
        {
            callback(result);
        }

        public void Start(Func<B, T> fun, B state)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(o =>
            {
                B b = o as B;
                T t;
                using (TimeStopwatch timeStopwatch = new TimeStopwatch())
                    t = fun(b);

                
                synchronizeInvoke.Invoke(new TestDelegate(InvokeCallback), new Object[] { t });
            }), state);
        }

        public void Start(Func<T> fun)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(o =>
            {
                T t = fun();
                synchronizeInvoke.Invoke(new TestDelegate(InvokeCallback), new Object[] { t });
            }));
        }
    }
}
